/**
 * 
 */
package sailing.ui.systemsetting.model;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import javax.swing.tree.TreeNode;

import sailing.entity.SubjectCategory;
import cjlite.logger.Logger;
import cjlite.utils.Lists;

/**
 * @author kevin
 * 
 */
public class SubjectTreeNode implements TreeNode {

	private static Logger logger = Logger.thisClass();

	private String nodeName;

	private SubjectTreeNode parent;

	private List<SubjectTreeNode> childList = Lists.newArrayList();

	private Object nodeValue;

	public SubjectTreeNode(String name) {
		this.nodeName = name;
	}

	public SubjectTreeNode(String name, Object value) {
		this.nodeName = name;
		this.nodeValue = value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#getChildAt(int)
	 */
	@Override
	public TreeNode getChildAt(int childIndex) {
		return childList.get(childIndex);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#getChildCount()
	 */
	@Override
	public int getChildCount() {
		return childList.size();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#getParent()
	 */
	@Override
	public TreeNode getParent() {
		return parent;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#getIndex(javax.swing.tree.TreeNode)
	 */
	@Override
	public int getIndex(TreeNode node) {
		logger.entry();
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#getAllowsChildren()
	 */
	@Override
	public boolean getAllowsChildren() {
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#isLeaf()
	 */
	@Override
	public boolean isLeaf() {
		if (nodeValue instanceof SubjectCategory) {
			return false;
		}
		return childList.size() == 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.tree.TreeNode#children()
	 */
	@Override
	public Enumeration children() {
		return Collections.enumeration(this.childList);
	}

	public void addChild(SubjectTreeNode stn) {
		childList.add(stn);
		stn.setParent(this);
	}

	private void setParent(SubjectTreeNode subjectTreeNode) {
		this.parent = subjectTreeNode;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		if (this.nodeValue != null) {
			return this.nodeValue.toString();
		}
		return this.nodeName;
	}

	public boolean isSubjectCategoryNode() {
		return this.nodeValue instanceof SubjectCategory;
	}

}
